import { dirname, resolve } from 'node:path'
import { cwd } from 'node:process'
import { fileURLToPath } from 'node:url'
import vue from '@vitejs/plugin-vue'
import UnoCSS from 'unocss/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import { defineConfig, loadEnv } from 'vite'
import { postcssPluginPrefix } from './build/postcss/postcss-plugin-prefix'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const __dirname = dirname(fileURLToPath(import.meta.url))
  const envs = loadEnv(mode, cwd())

  return {
    plugins: [
      vue(),
      UnoCSS(),
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: 'less', // 使用 less 样式
          }),
        ],
        include: [/\.vue$/, /\.vue\?vue/],
        dts: 'src/types/components.d.ts',
        dirs: ['src/components'],
      }),
    ],
    build: {
      rollupOptions: {
        output: {
          entryFileNames: 'js/[name].[hash:8].[format].js',
          chunkFileNames: 'js/[name].[hash:8].[format].js',
          assetFileNames: '[ext]/[name].[hash:8].[ext]',
        },
      },
      cssCodeSplit: false,
    },
    optimizeDeps: {
      exclude: ['@iconify-json/ant-design', 'ant-design-vue/es/locale/zh_CN'],
      include: ['axios'],
    },
    resolve: {
      alias: [
        { find: '@/', replacement: `${resolve(__dirname, './src')}/` },
      ],
    },
    define: {
      __DEV_IMG__: JSON.stringify('https://wechatapppro-1252524126.file.myqcloud.com/applo63nrk66621/image/b_u_5c2350154e829_vitcYpGa/m4xtbarj0ti4.jpeg'),
    },
    css: {
      postcss: {
        plugins: [
          postcssPluginPrefix({
            appPrefix: envs.VITE_APP_CLASS_PREFIX,
            shouldApplyAppPrefix(className) {
              return ['pc', 'mobile'].includes(className)
            },
          }),
        ],
      },
    },
    base: envs.VITE_APP_PUBLIC_PATH,
  }
})
